package landyer.tools.jdbcGenerator;

import landyer.tools.jdbcGenerator.ColumnBean;
import landyer.tools.jdbcGenerator.RenameField;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * User: landy
 * Date: 13-12-13
 * Time: 下午6:30
 */
public abstract class TableWapper {
    public static final int ORACLE=0;
    public static final int MYSQL=1;
    public List<ColumnBean> getColumns(Connection conn,String tableName) throws SQLException {
        List<ColumnBean> columnBeans=new ArrayList<ColumnBean>();
        Statement statement = conn.createStatement();
        ResultSetMetaData metaData = statement.executeQuery(getFirstLine(tableName)).getMetaData();
        for(int i=0;i<metaData.getColumnCount();i++){
            ColumnBean bean=new ColumnBean();
            //index 参考getColumns的javadoc
            int index=i+1;
            bean.setName(metaData.getColumnName(index));
            bean.setDataType(metaData.getColumnType(index));
            String columnClassName = metaData.getColumnClassName(index);

            bean.setTypeName(filter(columnClassName));
            bean.setAdjustName(RenameField.getFiledName(bean.getName()));
            columnBeans.add(bean);
        }
        statement.close();

        ResultSet primaryKeys = conn.getMetaData().getPrimaryKeys(null, null, tableName);
        if (primaryKeys.next()){
            String pkName = primaryKeys.getString(4);
            for(ColumnBean cb: columnBeans){
                if(cb.getName().equals(pkName)){
                    cb.setPrimaryKey(true);
                }else{
                    cb.setPrimaryKey(false);
                }
            }
        }else{
            throw new RuntimeException("Can't found Primary Key in table "+tableName);
        }
        return columnBeans;
    }

    protected  String filter(String columnClassName){
        if(columnClassName.contains("BigDecimal")){
            return "java.lang.Double";
        }
        return columnClassName;
    }

    protected abstract String getFirstLine(String tableName);

    public  ColumnBean getPrimaryKey(Connection conn,String tableName) throws SQLException{
        for(ColumnBean cb:getColumns(conn,tableName)){
            if(cb.isPrimaryKey()){
                return cb;
            }
        }
        return null;
    }

    public List<String> getTables(Connection conn,String schema) throws SQLException {
        List<String> tables=new ArrayList<String>();
        ResultSet tbRs = conn.getMetaData().getTables(null, schema, "%", new String[]{"TABLE"});
        while (tbRs.next()){
            tables.add(tbRs.getString(3));
        }
        return tables;
    }
}
